package backend.dal.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import backend.util.PropertyProvider;

public class SessionManager {

	private static final Logger LOG = LoggerFactory
			.getLogger(SessionManager.class);
	private static final SessionFactory sessionFactory = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {
		try {
			// Create the SessionFactoryfrom hibernate.cfg.xml
			// Setup connection using the PropertyProvider
			final Configuration configuration = new Configuration();
			configuration.configure();
			configuration.setProperty("hibernate.connection.username",
					PropertyProvider.INSTANCE.getProperty("dbUser"));
			configuration.setProperty("hibernate.connection.password",
					PropertyProvider.INSTANCE.getProperty("dbPassword"));
			configuration.setProperty("hibernate.connection.url",
					PropertyProvider.INSTANCE.getProperty("dbURL"));
			configuration.setProperty("hibernate.connection.pool_size",
					PropertyProvider.INSTANCE
							.getProperty("SIZE"));
			final ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
					.applySettings(configuration.getProperties()).build();
			return configuration.buildSessionFactory(serviceRegistry);
		} catch (final Throwable ex) {
			LOG.error("SessionFactoryinitialization failed", ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

}
